package com.firewolf.permission.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.firewolf.permission.constant.ConstantUtil;
import com.firewolf.permission.entities.Role;
import com.firewolf.permission.entities.User;
import com.firewolf.permission.service.impl.UserService;
import com.firewolf.permission.ui.EasyUIGridData;
import com.firewolf.permission.ui.Message;
import com.firewolf.permission.ui.Message.Status;

@Controller
@RequestMapping("user")
public class UserController {

	@Autowired
	private UserService uService;

	/**
	 * 登录
	 * 
	 * @param user
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping("login")
	public String login(User user, HttpSession session) {
		User u2 = uService.findUserForLogin(user);
		if (u2 == null) {
			return "err";
		} else {
			session.setAttribute(ConstantUtil.CURRENR_USER, u2);
			return "ok";
		}
	}

	/**
	 * 返回用户列表
	 * 
	 * @return
	 */
	@RequestMapping("list")
	@ResponseBody
	public EasyUIGridData userList(Integer page, Integer rows) {
		EasyUIGridData data = uService.finUsers(page, rows);
		return data;
	}

	/**
	 * 添加用户
	 * 
	 * @param u
	 * @return
	 */
	@RequestMapping("add")
	@ResponseBody
	public Message add(User u) {
		int i = uService.addUser(u);
		Message m = i == 0 ? new Message(Status.ERR, "添加失败!") : new Message();
		return m;
	}

	@RequestMapping("del")
	@ResponseBody
	public Message del(String ids) {
		int i = uService.deleteBatch(ids);
		return i == 0 ? new Message(Status.ERR, "删除用户失败!") : new Message();
	}

	@RequestMapping("tosetroles/{uid}")
	public String tosetroles(@PathVariable("uid") String uid, Map<String, Object> map) {
		map.put("uid", uid);
		return "user/setroles";
	}

	@RequestMapping("setroles")
	@ResponseBody
	public Message setroles(String roleids, Integer userid) {
		int c = uService.updateRoles(roleids, userid);
		if (c == 0) {
			return new Message(Status.ERR, "设置角色失败！");
		}
		return new Message("设置角色成功!");
	}

	@RequestMapping("roles/{userId}")
	@ResponseBody
	public List<Role> roles(@PathVariable("userId") Integer userId) {
		return uService.findAllRoles(userId);
	}
}
